const express = require('express');
const router = express.Router();
const path = require('path');
const mysql = require(path.join(__dirname, '../mysql'));
const {sleep} = require('@utils');

router.get('/', async (req, res) => {
    const r = await mysql.query('mysql', {sql: 'SELECT * FROM Computers'});
    res.json(r);
});

router.get('/item', function (req, res) {
    res.send('test-item');
});

router.get('/api/data', async (req, res) => {
    // throw new Error('test');
    // res.status(500).send('test'); // 发送500服务器错误
    const issEven = req.query.even === 'true';
    await new Promise((resolve) => setTimeout(resolve, 3000));
    res.json({
        code: 200,
        msg: 'success',
        data: {
            records: [
                {
                    name: '小杨',
                    age: 18,
                    sex: '男',
                    address: '北京',
                    phone: '123456789',
                    isEven: issEven,
                },
                {
                    name: '小李',
                    age: 22,
                    sex: '男',
                    address: '北京',
                    phone: '123456789',
                    isEven: issEven,
                },
            ],
        },
    });
});

router.get('/test1', async (req, res) => {
    console.log(req.headers);
    res.json('test1');
});

router.get('/test2', async (req, res) => {
    res.json('test2');
});

router.post('/refresh', async (req, res) => {
    res.send('refresh');
    res.json({
        code: 200,
        msg: 'success',
        data: {
            token: '123456789',
        },
    });
});

// ================== 以下为token相关功能实现 ==================

const expireTime = 10 * 1000;
// 生成简单的token字符串
function generateToken() {
    // 生成一个随机字符串作为token
    return (Date.now() + expireTime).toString();
}

// 获取初始token接口
// 前端首次调用此接口获取token
router.get('/api/get-token', (req, res) => {
    const token = generateToken();
    res.json({
        code: 200,
        msg: 'token获取成功',
        data: {
            token,
        },
    });
});

// 受保护的接口，调用次数超过限制就返回token过期
router.get('/api/protected', (req, res) => {
    // 从请求头获取token，前端需在请求头加authorization: token
    const token = req.headers['authorization'];
    let isExpire = parseInt(token) >= Date.now();
    // 检查token是否存在且有效
    if (!token || !isExpire) {
        // 没有token或token无效
        return res.status(401).json({code: 401, msg: 'token已过期，请刷新token'});
        return res.json({
            code: 401,
            msg: 'token已过期，请刷新token',
        });
    }
    res.json({
        code: 200,
        msg: '调用成功',
        data: {
            msg: '调用成功',
        },
    });
});

// 刷新token接口，返回新token并重置计数
router.post('/api/refresh-token', async (req, res) => {
    await sleep(5 * 1000);
    const newToken = generateToken();
    res.json({
        code: 200,
        msg: 'token刷新成功',
        data: {
            token: newToken,
        },
    });
});

module.exports = router;
